/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package user;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;


/**
 *
 * @author killian
 */
public class LoggingInterceptor implements Interceptor{
 
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(LoggingInterceptor.class);
 
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
 
        System.out.print("inside auth interceptor");
        Map<String, Object> sessionAttributes = actionInvocation.getInvocationContext().getSession();
         
        User userSession = (User) sessionAttributes.get("user");
        logger.info("user:"+userSession);
        
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
        String language = request.getParameter("request_locale");
        boolean requestLanguage = true;
        if(language == null) {
            requestLanguage = false;
        }
        else {
            if(!language.equals("en") && !language.equals("fr")) {
                requestLanguage = false;
            }
        }
        if(userSession == null && !requestLanguage){
            logger.warn("Accès interdit");  
            return Action.LOGIN;
        }else{
            logger.info("Accès autorisé"); 
            return actionInvocation.invoke();
        }
    }
 
    @Override
    public void destroy() {
        System.out.println("Destroying MyLoggingInterceptor...");
    }
    @Override
    public void init() {
        System.out.println("Initializing MyLoggingInterceptor...");
    }
}